package com.sxg.controller;

import com.sxg.annotation.Anonymous;
import com.sxg.constant.Constants;
import com.sxg.convert.SxgUserConvert;
import com.sxg.entity.SxgUserEntity;
import com.sxg.entity.vo.LoginBody;
import com.sxg.service.impl.SxgLoginService;
import com.sxg.utils.SecurityUtils;
import com.sxg.utils.code.AjaxResult;
import com.sxg.vo.req.RegisterReqVo;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@Validated
public class SxgLoginController {

    @Autowired
    private SxgLoginService sxgLoginService;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody @Valid LoginBody loginBody) {
        // 生成令牌
        String token = sxgLoginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        return AjaxResult.success().put(Constants.TOKEN, token);
    }

    /**
     * 退出登录方法
     *
     * @return 结果
     */
    @PostMapping("/logout")
    public AjaxResult logout(HttpServletRequest request) {
        return sxgLoginService.logout(request);
    }

    /**
     * 注册方法
     * @param vo 注册信息
     * @return
     */
    @PostMapping("/register")
    @Anonymous
    public AjaxResult register(@RequestBody @Valid RegisterReqVo vo) {

        return sxgLoginService.register(vo);
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("/getInfo")
    public AjaxResult getInfo() {
        SxgUserEntity user = SecurityUtils.getLoginUser().getSxgUserEntity();
        return AjaxResult.success(SxgUserConvert.INSTANCE.convert(user));
    }




}
